package com.yifeng.repo.controller.postman.work.task.handler.impl;

import com.google.common.base.Strings;
import com.talkyun.utils.MD5;
import com.yifeng.repo.controller.postman.work.dto.PostTaskDto;
import com.yifeng.repo.controller.postman.work.task.handler.PostInterceptor;
import org.springframework.http.MediaType;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;

import static com.yifeng.repo.controller.postman.work.constant.PostmanConstant.*;

/**
 * Created by daibing on 2023/7/21.
 */
public class SimplePostInterceptor implements PostInterceptor {

    /**
     * 注意处理业务投递参数中的占位符，变量类似 {{AccessKeyId.DATA}}，动作类似 {{Signature.ACTION}}
     */
    @Override
    public void apply(PostTaskDto postTaskDto) {
        // 1. method
        postTaskDto.setMethod(postTaskDto.getHttpRequestParam().getMethod());

        // 2. header
        Map<String, String> header = new TreeMap<>(postTaskDto.getHttpRequestParam().getHeader());
        header.put("Content-Type", postTaskDto.getHttpRequestParam().getContentType());
        postTaskDto.setHeader(header);

        // 3. body
        postTaskDto.setBody(this.buildRequestBody(postTaskDto).getBytes(StandardCharsets.UTF_8));

        // 4.url
        postTaskDto.setUrl(postTaskDto.getHttpRequestParam().getUri());
    }

    protected String buildRequestBody(PostTaskDto postTaskDto) {
        // 1. 检查是否空body
        String body = postTaskDto.getHttpRequestParam().getBody();
        if (Strings.isNullOrEmpty(body)) {
            if (postTaskDto.getHttpRequestParam().getContentType().toLowerCase().contains(MediaType.APPLICATION_JSON_VALUE)) {
                return "{}";
            } else {
                return "";
            }
        }

        // 2. 开始替换.DATA占位符
        StringBuffer sb = new StringBuffer();
        Matcher matcher = DATA_PATTERN.matcher(body);
        while (matcher.find()) {
            String dataKey = matcher.group().replaceAll(WRAP_DATA_KEY_REGEX, "");
            String paramsValue = String.valueOf(postTaskDto.getBizSystemParams().get(dataKey));
            matcher.appendReplacement(sb, paramsValue);
        }
        matcher.appendTail(sb);

        // 3. 如果业务系统参数未指定签名字段，就直接返回
        if (!postTaskDto.getBizSystemParams().containsKey(SIGN_FIELDS_KEY)) {
            return sb.toString();
        }

        // 4. 替换签名
        String[] fields = String.valueOf(postTaskDto.getBizSystemParams().get(SIGN_FIELDS_KEY)).split(",");
        StringBuilder sign = new StringBuilder();
        for (String field : fields) {
            if (postTaskDto.getBizSystemParams().containsKey(field)) {
                sign.append(postTaskDto.getBizSystemParams().get(field));
            } else {
                sign.append(field);
            }
        }
        return sb.toString().replace(LEFT_BRACKET + SIGN_ACTION_KEY + RIGHT_BRACKET, MD5.md5(sign.toString()));
    }

}
